package com.minisoft.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @author JueSu
 * @description: TODO
 * @date 2022/11/8 9:28
 */
@Slf4j
@ServerEndpoint(value = "/p2p")
@Component
public class P2PWebSocket {

    private static Session[] sessionContainer = new Session[2];


    /**
     * 连接
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        if (sessionContainer[0] == null && sessionContainer[1] == null) {
            sessionContainer[0] = session;
            log.info("A 用户接入");
        } else if (sessionContainer[0] != null && sessionContainer[1] == null) {
            sessionContainer[1] = session;
            log.info("B 用户接入");
        }

    }

    /**
     * 断开连接
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        for (int i = 0; i < sessionContainer.length; i++) {
            if (session == sessionContainer[i]) {
                sessionContainer[i] = null;
                log.info("{}用户已注销",i == 0 ? "A":"B");
            }
        }

    }

    public Session getOtherSession(Session session) {
        if (session == sessionContainer[0]) {
            return sessionContainer[1];
        }
        return sessionContainer[0];
    }

    /**
     * 收到消息
     * @param message
     * @param session
     * @throws IOException
     */
    @OnMessage
    public void sendMsg(String message,Session session) throws IOException {
        Session otherSession = getOtherSession(session);
        otherSession.getBasicRemote().sendText(message);
    }

    /**
     * 异常处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session,Throwable error) {
        log.error("error",error);
    }
}
